<?php
namespace Admin\Controller;
use Admin\Controller\BaseController;

class MyHomeworkController extends BaseController {

	protected $studentId = null;

	protected $logicClassIds = array();

	protected function _initialize() {
		parent::_initialize();
		$this->studentId = I('session.uid');
		$this->logicClassIds = M('LogicClassStudent')
			->where(array('student_id' => $this->studentId))
			->getField('logic_class_id', true);
	}

	public function index() {
		if(IS_POST) {
			$logicClassId = I('post.logic_class_id');
		} else {
			$logicClassId = $this->logicClassIds[0];
		}
		$map['id'] = array('in', $this->logicClassIds);
		$this->logicClassIds && $logicClasses = M('LogicClass')->where($map)->select();
		$homeworks = M('Homework')->where(array('logic_class_id' => $logicClassId))->select();
		$this->assign('logic_class_id', $logicClassId);
		$this->assign('logic_classes', $logicClasses);
		$this->assign('homeworks', $homeworks);
		$this->display();
	}

	public function detail() {
		$homeworkId = I('homework_id');
		$this->assign('homework', M('Homework')->where(array('id' => $homeworkId))->find());
		$this->display();
	}

	public function submit() {
		$homeworkId = I('homework_id');
		$this->assign('homework_id', $homeworkId);
		$this->display();
	}

	public function submitPost() {
		if(!IS_POST) {
			$this->redirect('Homework/index');
		}
		$homeworkId = I('post.homework_id');
		$upload = new \Think\Upload();
		$upload->exts = array('doc', 'docx');
		$result = $upload->upload();
		if(!$result) {
			$this->error($upload->getError());
		}
		$data['submit_time'] = time();
		$data['file_name'] = $result['file']['name'];
		$data['file_savename'] = $result['file']['savename'];
		$data['file_savepath'] = $upload->rootPath . $result['file']['savepath'];
		$map['homework_id'] = $homeworkId;
		$map['student_id'] = $this->studentId;
		// 如果作业已经提交过一次，则更新之前的记录
		if($temp = M('HomeworkStudent')->where($map)->find()) {
			if(M('HomeworkStudent')->where(array('id' => $temp['id']))->data($data)->save()) {
				$this->success('提交成功！', U('MyHomework/index'), 0);
			} else {
				$this->error('更新学生作业失败！');
			}
		} else {
			// 如果作业从未提交过，则新加一条记录
			$data['homework_id'] = $homeworkId;
			$data['student_id'] = $this->studentId;
			if(M('HomeworkStudent')->data($data)->add()) {
				$this->success('提交成功！', U('MyHomework/index'), 0);
			} else {
				$this->error('写入学生作业失败！');
			}			
		}
	}

}
